#include "SeqList.h"

// 对数据的基本操作:增删查改 
void SeqListInit(SeqList* ps, size_t InitCapacity)
{
	assert(ps);
	ps->arr = (int *)malloc(sizeof(SLDateType)*InitCapacity);
	if (NULL == ps->arr){         //申请空间失败
		assert(0);
		return;
	}
	ps->capacity = 0;
	ps->size = 0;
}


void SeqListDestory(SeqList* ps)
{
	assert(ps);
	if (ps->arr){
		free(ps->arr);
		ps->arr = NULL;
		ps->capacity = 0;
		ps->size = 0;
	}
}

void SeqListPrint(SeqList* ps)
{
	assert(ps);
	if (ps->arr){
		for (int i = 0; i < ps->size; i++){
			printf("%d ", ps->arr[i]);
		}
	}
	printf("\n");
}

int SeqListEmpty(SeqList* ps)          //判空
{
	assert(ps);
	return(0 == ps->size);
}

void CheckCapacity(SeqList* ps)                   //扩容
{
	assert(ps);
	if (ps->size == ps->capacity){
		(ps->capacity) *= 2;
		int* temp = (int*)malloc(sizeof(SLDateType)*(ps->capacity));
		if (NULL == ps->arr){         //申请空间失败
			assert(0);
			return;
		}

		memcpy(temp, ps->arr, sizeof(SLDateType)*(ps->size));
		free(ps->arr);
		ps->arr = temp;
	}
}

void SeqListPushBack(SeqList* ps, SLDateType x)        //尾插
{
	assert(ps);
	CheckCapacity(ps);               //检验容量，不够扩容

	ps->arr[ps->size] = x;
	ps->size++;
}

void SeqListPushFront(SeqList* ps, SLDateType x)       //头插
{
	assert(ps);
	//CheckCapacity(&ps);               //检验容量，不够扩容
	if (SeqListEmpty(ps)){
		ps->arr[0] = x;
   }
	else{
		for (int i = ps->size; i > 0; i--){
			ps->arr[i] = ps->arr[i - 1];
		}
		ps->arr[0] = x;
	}
	ps->size++;
}

void SeqListPopFront(SeqList* ps)                      //头删
{
	assert(ps); 
	if (SeqListEmpty(ps)){                        //检验是否为空
		return;
	}
	for (int i = 1; i < (ps->size); i++){
		ps->arr[i - 1] = ps->arr[i];
	}
	ps->size--;
}

void SeqListPopBack(SeqList* ps)						 //尾删
{
	assert(ps);
	if (SeqListEmpty(ps)){                        //检验是否为空
		return;
	}
	ps->arr[(ps->size) - 1] = NULL;
	ps->size--;
}


// 顺序表查找
int SeqListFind(SeqList* ps, SLDateType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++){
		if (ps->arr[i] == x){
			return i;
		}
	}
	return -1;
}

// 顺序表在pos位置插入x
void SeqListInsert(SeqList* ps, size_t pos, SLDateType x)
{
	assert(ps);
	if (pos <= 0 || pos > ps->size + 1){              //位置[1,size+1]为合理位置（默认从1开始）
		printf("pos error!\n");
		return;
	}
	CheckCapacity(ps);                            // 是否需要扩容
	for (int i = ps->size; i > pos-1; i--){
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos - 1] = x;
	ps->size++;

}

// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, size_t pos)
{
	assert(ps);
	if (pos <= 0 || pos > ps->size + 1){               //位置[1,size+1]为合理位置（默认从1开始）
		printf("pos error!\n");
		return;
	}
	for (int i = pos; i < ps->size; i++){
		ps->arr[i - 1] = ps->arr[i];
	}
	ps->size--;
}